import {
  useState,
  useEffect,
  Fragment,
  createContext,
  useRef,
  useContext
} from 'react';
import { Button, message, Table, Form, Input } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import { http } from '@/utils/http';
const EditableContext = createContext(null);

export default function NewsCategory() {
  const [categoryList, setCategoryList] = useState([])  // 新闻分类列表数据

  // 获取新闻分类列表
  const getCategoryList = async () => {
    const { data } = await http.get('/categories')
    setCategoryList(data)
  }

  useEffect(() => {
    getCategoryList()
  }, [])

  // 点击删除按钮的回调
  const onClickDelete = id => {
    http.delete(`/categories/${id}`)
      .then(() => {
        setCategoryList(categoryList.filter(item => item.id !== id))
        message.success('删除分类成功！', 2)
      })
      .catch(() => {
        message.error('request失败！', 2)
      })
  }

  // 处理保存编辑的单元格
  const handleSave = record => {
    const index = categoryList.findIndex(item => item.id === record.id)
    record.title === categoryList[index].title ?
      message.info('似乎什么也没有发生…', 2)
      :
      http.patch(`/categories/${record.id}`, {
        title: record.title,
        value: record.title
      })
        .then(() => {
          setCategoryList(categoryList.map(item => {
            if (item.id === record.id) {
              return {
                ...item,
                title: record.title,
                value: record.title
              }
            }
            return item;
          }))
          message.success('修改分类标题成功！', 2)
        })
        .catch(() => {
          message.error('Save failed！', 2)
        })
  }

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      align: 'center',
      render: id => <b>{id}</b>
    },
    {
      title: <Fragment>
        栏目名称
        <br />
        Click cells under this column to edit the title
      </Fragment>,
      dataIndex: 'title',
      width: '40%',
      align: 'center',
      onCell: record => ({
        record,
        title: '栏目名称',
        dataIndex: 'title',
        editable: true,  // 可编辑的单元格
        handleSave,
      }),
    },
    {
      title: '操作',
      align: 'center',
      render: ({ id }) => <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => onClickDelete(id)} />
    }
  ]

  // 可编辑的行
  const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();  // 创建form实例对象
    return (
      <Form form={form} component={false}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };

  // 可编辑的单元格
  const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);  // 是否处于编辑状态
    const inputRef = useRef(null);  // input框的ref对象
    const form = useContext(EditableContext);  // 接收form实例对象
    useEffect(() => {
      if (editing) {
        inputRef.current.focus();  // 处于编辑状态时，input框获取焦点
      }
    }, [editing]);

    // 切换编辑状态，保存编辑内容
    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({
        [dataIndex]: record[dataIndex],
      });
    };

    const save = async () => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({ ...record, ...values });
      } catch (errInfo) {
        console.log('Save failed:', errInfo);
      }
    };

    let childNode = children;

    if (editable) {
      childNode = editing ? (  // 编辑状态
        <Form.Item
          style={{
            margin: 0,
          }}
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `${title}不能为空！`,
            },
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (  // 非编辑状态
        <div
          className="editable-cell-value-wrap"
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }
    // 若不可编辑的单元格，直接return原内容
    return <td {...restProps}>{childNode}</td>;
  };

  return (
    <Fragment>
      <Table
        columns={columns}
        dataSource={categoryList}
        rowKey={item => item.id}
        components={{
          body: {
            row: EditableRow,
            cell: EditableCell
          }
        }}
      />
    </Fragment>
  )
}